const projectName = process.argv[2]
const sfsPageLists = require('./pageLists.js')

const projectPageConfigPath =
  './src/projects/' + projectName + '/pageConfig.txt'

let fs = require('fs')
// 文件配置列表写入路径
const pageUtilDir = './src/sfs-example/utils/'
// 当前项目路径前缀
const proFilePath = 'projects/' + projectName

// 记录正在运行的项目名
fs.writeFileSync('./config/project.js', `exports.name = '${projectName}'`)

// 读取当前项目的修改内容
const docu = fs.readFileSync(projectPageConfigPath)
const projectContent = docu.toString().split(',')

function runSetConfig() {
  console.log('设置配置')
  let findid = JSON.parse(JSON.stringify(sfsPageLists))
  let fixList = null
  if (projectContent && projectContent.length > 0) {
    for (let i = 0; i < projectContent.length; i++) {
      console.log('当前项目修改项::::', projectContent[i])
      // 查找并修改路径
      fixList = findPath(findid, proFilePath, projectContent[i])
      findid = fixList
    }
    // 写
    writePageUtil(pageUtilDir + 'project-pageList.js', findid)
  }
}

// 写入页面列表配置文件
function writePageUtil(path, con) {
  fs.writeFileSync(
    path,
    'const pageLists = ' + JSON.stringify(con) + '\n\r export { pageLists }',
  )
}

function findPath(arr, proFilePath, id) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id === id) {
      const findFeilPath =
        './src/' + proFilePath + '/views/' + arr[i]['basePath']
      if (isExistFile(findFeilPath)) {
        arr[i].path = proFilePath
      } else {
        console.log(id + ' 所对应的文件不存在')
      }
    } else {
      if (arr[i].children && arr[i].children.length) {
        for (let j = 0; j < arr[i].children.length; j++) {
          findPath(arr[i].children, proFilePath, id)
        }
      }
    }
  }
  return arr
}

// 判断文件是否存在
function isExistFile(filePath) {
  try {
    fs.statSync(filePath)
    return true
  } catch (error) {
    return false
  }
}

module.exports.run = runSetConfig

// 读
// const docu = fs.readFileSync('path')

// 写
// fs.writeFileSync('path', docu)

// 删
// fs.unlinkSync('path')
